#!/usr/bin/env python
# -* coding: utf-8 -*-

#Author: Gustaw Lewandowski
#Licence : GPL

import os
import time
import urwid
from utils import divider, log, setup, ListWalkerBase, ListBoxBase, ListBoxSB, Border
from ucp import UrwidCmdProc, urwidcmd, utf8decode, isUCP

class FileWidget(urwid.AttrWrap):
	def __init__(self, name, fileType):
		self.widget = urwid.Text(name)
		if fileType == 1:
			attr = 'dir'
		else:
			attr = 'file'
		self.__super.__init__(self.widget , attr, 'focus')
		self.name = name
		self.fileType = fileType
		self.selected = False
		self.timemp = time.time() - 5.0
		self.edit_mode = False
	def mouse_event(self, size, event, button, col, row, focus):
		""" handle slow ouble click """ 
		if event == 'mouse press' and button == 1:

			ntimemp = time.time()
			timeDelta = ntimemp - self.timemp
			if timeDelta > 0.5 and timeDelta < 2.0:
				self.start_edit_mode()
			elif timeDelta <= 0.5:
				log.info('ccclick')
				return 'click'
			self.timemp = time.time()        	    

	def keypress(self, (maxcol,), key):
		log.info(key)
		if self.edit_mode == True:
			if key == "enter":
				new_name = self.exit_edit_mode()
				if new_name is not None:
					return (urwidcmd, UrwidCmdProc.rename, self.name, new_name)   
			else:		
				self.edit_widget.keypress((maxcol,), key)
		elif key == "insert":
			if self.selected == False:
				self.attr = 'selectedfile'
				self.focus_attr = 'selectedfocus'
				self.selected = True
				return 'down'
			self.set_attr()
			self.selected = False
		elif key == 'z':
			self.start_edit_mode()
		return key

	def selectable(self):
		return True

	def set_attr(self):
		if self.fileType == 1:
			self.attr = 'dir'
		else:
			self.attr = 'file'
		self.focus_attr = 'focus'

	def start_edit_mode(self):
		self.edit_widget = urwid.Edit("",self.name)
		self.set_w(self.edit_widget)
		self.attr = 'fileedit'
		self.focus_attr = self.attr
		self.edit_mode = True

	def exit_edit_mode(self):
		self.set_w(self.widget)
		if self.fileType == 1:
			self.attr = 'dir'
		else:
			self.attr = 'file'
		self.focus_attr = 'focus'
		self.edit_mode = False
		new_name = self.edit_widget.get_edit_text()
		if new_name in (self.name, ""):
			new_name = None
		del self.edit_widget
		return new_name

class DirWalker(ListWalkerBase):
	def __init__(self):
		self.readdir(os.getcwd())

	def focus_dir_entry(self):
		if self.get_focus_entry().fileType == 1: # is directory
			dir_name = self.get_focus_entry().name
			if dir_name == "..":
				old_dir = self.path
			else:
				self.oldfocus = 0
			self.readdir(os.path.join(self.path, dir_name))
			if dir_name == "..":
				# set focus to last directory
				for i in range(0, self.size):
					if self.lines[i].name == old_dir:
						self.set_focus(i)
						break

	def get_full_path(self, file_name):
		 return os.path.join(self.path, file_name)

	def get_focused_filename(self):
		 return os.path.join(self.path, self.get_focus_entry().name)

	def reread_dir(self):
		self.oldfocus = self.focus
		self.readdir(self.path)

	def readdir(self, dirName):
		self.size = 1
		self.focus, self.oldfocus = self.oldfocus, self.focus
		self.lines = []
		self.path = os.path.normpath(dirName)
		dirs=[]
		files=[]
		try:
			# separate dirs and files
			for a in os.listdir(dirName):
				if os.path.isdir(os.path.join(dirName, a)):
					dirs.append(a)
				else:
					files.append(a)
				self.size += 1
		except OSError, e:
			self.size = 0
			self.lines.append(FileWidget(e))

		files.sort()
		dirs.sort()
		
		if self.path == "/":
			self.size -= 1
		else:
			self.lines.append(FileWidget("..", 1))

		for i in dirs:
			self.lines.append(FileWidget(i, 1))
		for i in files:
			self.lines.append(FileWidget(i, 0))
		if self.size < (self.focus+1):
			self.focus = self.size-1
		self._modified()

	def get_selected(self):
		ret = []
		for x in self.lines:
			if x.selected == True:
				ret.append(self.get_full_path(x.name))
		return ret

class DirBox(ListBoxBase):
	""" dirBox is needed for serve 'home' and 'end' keypress """
	def __init__(self):
		return self.__super.__init__(DirWalker())

	def keypress(self,(maxcol,maxrow), key):
		if key == "enter":
			self.body.focus_dir_entry()
		elif key in ("delete", "f8"):
			selected = self.body.get_selected()
			l_selected = len(selected)
			if l_selected == 0:
				return (urwidcmd, UrwidCmdProc.delete, self.body.get_focused_filename())
			if l_selected == 1:
				return (urwidcmd, UrwidCmdProc.delete, selected[0])
			return (urwidcmd, UrwidCmdProc.mdelete, selected)
		elif key == 'f4' and self.body.get_focus_entry().fileType == 0:
			return (urwidcmd, UrwidCmdProc.edit, self.body.get_focused_filename())

		rc = self.__super.keypress((maxcol, maxrow), key)
		if rc == 'click':
			 self.body.focus_dir_entry()
		elif isUCP(rc):
			if rc[1] == UrwidCmdProc.rename:
				# add full path
				j, j, fn1, fn2 = rc
				fn1 = self.body.get_full_path(fn1)
				fn2 = self.body.get_full_path(fn2)
				return (urwidcmd, UrwidCmdProc.rename, fn1, fn2)
		return rc

class DirPanel(urwid.Columns):
	def __init__(self, list=None):
		if setup.frameDirView == True:
			self.__super.__init__([Border(ListBoxSB(DirBox()), attr='dir'), Border(ListBoxSB(DirBox()), attr='dir')])
		else:
			# create column object with 3 widgets
			self.__super.__init__([ListBoxSB(DirBox()), divider, ListBoxSB(DirBox())])
		setup.dirWidget = self

	def with_frame(self, t_f):
		"""Switch beetween frame and not"""
		if t_f == True and len(self.widget_list) == 3:
			self.__super.__init__([Border(self.widget_list[0], attr='dir'),\
						Border(self.widget_list[2], attr='dir')])
		elif t_f == False and len(self.widget_list) == 2:
			self.__super.__init__([self.widget_list[0].get_widget(),\
					       divider,\
					       self.widget_list[1].get_widget()])

	def keypress(self, (maxcol,maxrow), key):
		""" Columns switching """
		if key in ("tab", "left", "right"):
			self.set_focus(self.get_unfocus_column())
		elif key == 'f5':
			selected = self.get_focus().body.get_selected()
			l_selected = len(selected)
			if l_selected == 0:
				return (urwidcmd, UrwidCmdProc.copy, self.get_focus().body.get_focused_filename(),\
					os.path.join(self.get_unfocus_column().body.path, self.get_focus().body.get_focus_entry().name))
			if l_selected == 1:
				return (urwidcmd, UrwidCmdProc.copy, selected[0], self.get_unfocus_column().body.path)
			return (urwidcmd, UrwidCmdProc.mcopy, selected, self.get_unfocus_column().body.path)
		elif key == 'f6':
			selected = self.get_focus().body.get_selected()
			l_selected = len(selected)
			if l_selected == 0:
				return (urwidcmd, UrwidCmdProc.move, self.get_focus().body.get_focused_filename(),\
					os.path.join(self.get_unfocus_column().body.path, self.get_focus().body.get_focus_entry().name))
			if l_selected == 1:
				return (urwidcmd, UrwidCmdProc.move, selected[0], self.get_unfocus_column().body.path)
			return (urwidcmd, UrwidCmdProc.mmove, selected, self.get_unfocus_column().body.path)
		elif key == 'f7':
			return (urwidcmd, UrwidCmdProc.mkdir, self.get_focus().body.path)
		rc = self.__super.keypress((maxcol, maxrow), key)
		if isUCP(rc):
			None
		return rc

	def get_unfocus_column(self):
		""" Get unfocussed column """
		if self.get_focus_column() == 0:
			return self.widget_list[-1]
		return self.widget_list[0]

	def get_focused_file_name(self):
		focus = self.get_focus().body
		# is file?
		if focus.get_focus_entry().fileType == 0:
			return os.path.join(focus.path, focus.get_focus_entry().name)
		return None

	def refresh_dirs(self):
		self.get_focus().body.reread_dir()
		self.get_unfocus_column().body.reread_dir()

	def refresh_focus_dir(self):
		self.get_focus().body.reread_dir()
		if self.get_focus().body.path == self.get_unfocus_column().body.path:
			self.get_unfocus_column().body.set_lines(self.get_focus().body.lines)
__all__ = ['DirPanel']
